<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms :modelValue="formData">
      <!-- 加工食品名称 -->
      <uni-card title="加工食品名称" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.jiaGongShiPinMingCheng"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 加工食品重量 -->
      <uni-card title="加工食品重量(g)" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.jiaGongShiPinZhongLiang"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <!-- 加工食品重量图片 -->
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.jiaGongShiPinZhongLiangImg"
            mode="grid"
            @select="uploadByjiaGongShiPinZhongLiangImg"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 食品添加剂名称 -->
      <uni-card title="食品添加剂名称" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiPinTianJiaJiMingCheng"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食品添加剂批次或生产日期 -->
      <uni-card title="食品添加剂批次或生产日期" extra="必填*">
        <uni-forms-item>
          <uni-datetime-picker
            type="date"
            :clear-icon="false"
            v-model="formData.date"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食品添加剂现存量(g) -->
      <uni-card title="食品添加剂现存量(g)" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiPinTianJiaJiXianCunLiang"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食品添加剂实际添加量(g) -->
      <uni-card title="食品添加剂实际添加量(g)" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiPinTianJiaJiShiJiTianJiaLiang"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食品添加剂剩余量(g) -->
      <uni-card title="食品添加剂剩余量(g)" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiPinTianJiaJiShengYuLiang"
            :disabled="isEdit"
          />
        </uni-forms-item>
        <!-- 食品添加剂剩余量(g)图片 -->
        <uni-forms-item>
          <uni-file-picker
            file-mediatype="image"
            v-model="formData.shiPinTianJiaJiShengYuLiangImg"
            mode="grid"
            @select="uploadByshiPinTianJiaJiShengYuLiangImg"
            :disabled="isEdit"
          ></uni-file-picker>
        </uni-forms-item>
      </uni-card>
      <!-- 使用者签字 -->
      <uni-card title="使用者签字" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.shiYongZheQianZi"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <uni-card title="评语" v-show="props.id">
        <uni-easyinput v-model="reviewOpinion" />
      </uni-card>
    </uni-forms>
    <button
      @click="submitForm"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
    >
      {{ submitBtnName }}
    </button>
    <ShowConfigComponent
      v-show="!isEdit"
      name="tianJiaJiShiYong"
      @showFormData="showFormData"
    />
  </scroll-view>
</template>

<script lang="ts" setup>
import {
  convertToString,
  getTodayDate,
  transformData,
  compareLoadData,
} from '@/utils/utils';
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { createTableById, showTableById, submitTable } from '@/services/write';
import type {
  FormDetail,
  returnSubmitData,
  submitTableData,
  tableDate,
} from '@/services/types/write';
import type { RequestMenuIdList } from '@/services/types/review';
import { submitMenuIdList } from '@/services/review';
import { uploadImg } from '@/utils/http';
// 表格提交信息
const formData = ref({
  jiaGongShiPinMingCheng: '', //加工食品名称
  jiaGongShiPinZhongLiang: '', //加工食品重量
  jiaGongShiPinZhongLiangImg: [] as {
    url: string;
    extname: string;
    name: string;
  }[], //加工食品重量图片
  shiPinTianJiaJiMingCheng: '', //食品添加剂名称
  date: ref(getTodayDate()).value, //食品添加剂批次或生产日期
  shiPinTianJiaJiXianCunLiang: '', //食品添加剂现存量(g)
  shiPinTianJiaJiShiJiTianJiaLiang: '', //食品添加剂实际添加量(g)
  shiPinTianJiaJiShengYuLiang: '', //食品添加剂剩余量(g)
  shiPinTianJiaJiShengYuLiangImg: [] as {
    url: string;
    extname: string;
    name: string;
  }[], //食品添加剂剩余量(g)图片
  shiYongZheQianZi: '', //使用者签字
});
// 上传 加工食品重量图片
const uploadByjiaGongShiPinZhongLiangImg = (e: UniHelper.PickerInstance) => {
  uploadImg(e).then((res) => {
    formData.value.jiaGongShiPinZhongLiangImg.push({
      url: res.url,
      extname: 'jpg',
      name: res.key,
    });
  });
};
// 上传 食品添加剂剩余量(g)图片
const uploadByshiPinTianJiaJiShengYuLiangImg = (
  e: UniHelper.PickerInstance,
) => {
  uploadImg(e).then((res) => {
    formData.value.shiPinTianJiaJiShengYuLiangImg.push({
      url: res.url,
      extname: 'jpg',
      name: res.key,
    });
  });
};
// 是否可编辑
const isEdit = ref(false);
// 提交按钮名字
const submitBtnName = ref('');
const props = defineProps({
  value: String,
  id: String,
});
// 评语
const reviewOpinion = ref('');
/**
 * 表格相关数据
 */
const table = () => {
  const tableData = ref<tableDate[]>([]);
  const reportingFormOperateId = ref('');
  // 如果提交按钮等于提交则创建表格
  const createTable = async () => {
    submitBtnName.value = '提交';
    // 创建表格
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    const res = await createTableById('8286263825078222848');
    reportingFormOperateId.value = res.reportingFormOperateId;
    tableData.value = res.data;
    uni.hideLoading();
  };
  // 提交表格
  const submitNewTable = (
    reportingFormOperateId: string,
    tableData: tableDate[],
  ): submitTableData => {
    const formDetail = transformData(tableData) as FormDetail[];
    //加工食品名称
    formDetail[0].componentValue = formData.value.jiaGongShiPinMingCheng;
    //加工食品重量
    formDetail[1].componentValue = formData.value.jiaGongShiPinZhongLiang;
    //加工食品重量图片
    if (formData.value.jiaGongShiPinZhongLiangImg.length) {
      formDetail[2].componentValue = convertToString(
        formData.value.jiaGongShiPinZhongLiangImg as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    //食品添加剂名称
    formDetail[3].componentValue = formData.value.shiPinTianJiaJiMingCheng;
    //食品添加剂批次或生产日期
    formDetail[4].componentValue = formData.value.date;
    //食品添加剂现存量(g)
    formDetail[5].componentValue = formData.value.shiPinTianJiaJiXianCunLiang;
    //食品添加剂实际添加量(g)
    formDetail[6].componentValue =
      formData.value.shiPinTianJiaJiShiJiTianJiaLiang;
    //食品添加剂剩余量(g)
    formDetail[7].componentValue = formData.value.shiPinTianJiaJiShengYuLiang;
    //食品添加剂剩余量(g)图片
    if (formData.value.shiPinTianJiaJiShengYuLiangImg.length) {
      formDetail[8].componentValue = convertToString(
        formData.value.shiPinTianJiaJiShengYuLiangImg as {
          url: string;
          extname: string;
          name: string;
        }[],
      );
    }
    //使用者签字
    formDetail[9].componentValue = formData.value.shiYongZheQianZi;
    // 其他数据
    const submitTable = ref<submitTableData>({
      formDetail: formDetail,
      reportingFormOperateId: reportingFormOperateId,
      status: 1,
      unionMenuId: '8286263825078222848',
    });

    return submitTable.value;
  };
  return {
    createTable,
    tableData,
    reportingFormOperateId,
    submitNewTable,
  };
};
const { createTable, submitNewTable, tableData, reportingFormOperateId } =
  table();
// 根据id展示数据
const showDataById = async (id: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await showTableById(id);
  if (res.msg === 'success') {
    //加工食品名称
    formData.value.jiaGongShiPinMingCheng =
      res.data.formDetail[0].componentValue;
    //加工食品重量
    formData.value.jiaGongShiPinZhongLiang =
      res.data.formDetail[1].componentValue;
    //加工食品重量图片
    if (res.data.formDetail[2].tfiles) {
      formData.value.jiaGongShiPinZhongLiangImg = [];
      res.data.formDetail[2].tfiles.map((item) => {
        formData.value.jiaGongShiPinZhongLiangImg.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    //食品添加剂名称
    formData.value.shiPinTianJiaJiMingCheng =
      res.data.formDetail[3].componentValue;
    //食品添加剂批次或生产日期
    formData.value.date = res.data.formDetail[4].componentValue;
    //食品添加剂现存量(g)
    formData.value.shiPinTianJiaJiXianCunLiang =
      res.data.formDetail[5].componentValue;
    //食品添加剂实际添加量(g)
    formData.value.shiPinTianJiaJiShiJiTianJiaLiang =
      res.data.formDetail[6].componentValue;
    //食品添加剂剩余量(g)
    formData.value.shiPinTianJiaJiShengYuLiang =
      res.data.formDetail[7].componentValue;
    //食品添加剂剩余量(g)图片
    if (res.data.formDetail[8].tfiles) {
      formData.value.shiPinTianJiaJiShengYuLiangImg = [];
      res.data.formDetail[8].tfiles.map((item) => {
        formData.value.shiPinTianJiaJiShengYuLiangImg.push({
          url: item.fileUrl,
          extname: 'jpg',
          name: item.name,
        });
      });
    }
    //使用者签字
    formData.value.shiYongZheQianZi = res.data.formDetail[9].componentValue;
    // 评语
    reviewOpinion.value = (
      res.data as returnSubmitData
    ).handleOption.reviewOpinion;
  }
  uni.hideLoading();
};
onLoad(async () => {
  // 判断提交按钮是否等于newTable，
  // 等于newTable则执行创建表格
  if (props.value === 'newTable') {
    createTable();
  } else if (props.id) {
    showDataById(props.id);
    submitBtnName.value = '审批';
    isEdit.value = true;
  }
});
// 提交
const submitForm = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        // 等于newTable则执行提交表格
        if (props.value === 'newTable') {
          submitTable(
            submitNewTable(reportingFormOperateId.value, tableData.value),
          ).then((res) => {
            if (res.msg === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        } else if (props.id) {
          // 有id意味查看详情
          const data = ref<RequestMenuIdList>({
            id: props.id,
          });
          submitMenuIdList(data.value, reviewOpinion.value).then((res) => {
            if (res.data === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 加载配置
const showFormData = (data: any) => {
  compareLoadData(formData.value, data);
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
